package flc.ast.fragment;

import android.net.Uri;
import android.os.Bundle;

import androidx.fragment.app.Fragment;

import android.os.Handler;
import android.os.StatFs;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.blankj.utilcode.util.ConvertUtils;
import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.stark.apkextract.lib.model.AeUtil;
import com.stark.picselect.config.PhotoConfig;
import com.stark.picselect.entity.SelectMediaEntity;
import com.stark.picselect.utils.MediaLoadManager;

import java.util.ArrayList;
import java.util.List;

import flc.ast.R;
import flc.ast.activity.AppActivity;
import flc.ast.activity.AudioActivity;
import flc.ast.activity.DocumentActivity;
import flc.ast.activity.PictureActivity;
import flc.ast.activity.VideoActivity;
import flc.ast.bean.MyDocumentBean;
import flc.ast.databinding.FragmentManageBinding;
import flc.ast.utils.MyUtils;
import io.reactivex.rxjava3.core.ObservableEmitter;
import stark.common.basic.base.BaseNoModelFragment;
import stark.common.basic.device.StorageUtil;
import stark.common.basic.event.EventStatProxy;
import stark.common.basic.media.MediaInfo;
import stark.common.basic.media.MediaLoader;
import stark.common.basic.media.bean.AudioBean;
import stark.common.basic.utils.RxUtil;
import stark.common.basic.utils.StkPermissionHelper;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link ManageFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class ManageFragment extends BaseNoModelFragment<FragmentManageBinding> {


    @Override
    protected int onCreate() {
        return R.layout.fragment_manage;
    }

    @Override
    protected void initView() {
        EventStatProxy.getInstance().statEvent1(getActivity(), mDataBinding.event1Container);
        EventStatProxy.getInstance().statEvent5(getActivity(), mDataBinding.event5Container);

        mDataBinding.llFilePicture.setOnClickListener(this);
        mDataBinding.llFileVideo.setOnClickListener(this);
        mDataBinding.llFileDocument.setOnClickListener(this);
        mDataBinding.llFileAudio.setOnClickListener(this);
        mDataBinding.llFileApp.setOnClickListener(this);
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.llFilePicture://图片
                getPermission(PictureActivity.class);
                break;
            case R.id.llFileVideo://视频
                getPermission(VideoActivity.class);
                break;
            case R.id.llFileDocument://文档
                getPermission(DocumentActivity.class);
                break;
            case R.id.llFileAudio://音频
                getPermission(AudioActivity.class);
                break;
            case R.id.llFileApp://应用
                getPermission(AppActivity.class);
                break;
        }
    }

    @Override
    protected void initData() {

    }

    @Override
    public void onResume() {
        super.onResume();
        setStorageData();
    }

    private void getPermission(Class cls) {
        StkPermissionHelper.reqManageExternalStoragePermission()
                .reqPermissionDesc(getString(R.string.get_manage_permission))
                .callback(new StkPermissionHelper.ACallback() {
                    @Override
                    public void onGranted() {
                        startActivity(cls);
                    }
                }).request();
    }

    //设置存储数据
    private void setStorageData() {
        StatFs statFs = StorageUtil.getInternalMemory();//内部存储
        //已使用
        long usedLong = statFs.getTotalBytes() - statFs.getAvailableBytes();
        //总内存
        long allLong = statFs.getTotalBytes();
        //已用百分比
        int progress = (int) ((statFs.getTotalBytes() - statFs.getAvailableBytes()) * 100f / statFs.getTotalBytes());
        mDataBinding.tvStorage.setText(ConvertUtils.byte2FitMemorySize(usedLong, 0) + "/" + ConvertUtils.byte2FitMemorySize(allLong, 0));
        mDataBinding.tvPercent.setText(getString(R.string.used_storage) + progress + getString(R.string.unit_percent));
        mDataBinding.sbFile.setProgress(progress);
        //设置文件数量
        getPictureNum(usedLong);
        getVideoNum(usedLong);
        getDocNum(usedLong);
        getAudioNum(usedLong);
        getAppNum(usedLong);
    }

    //获取图片大小
    private void getPictureNum(long memory) {
        RxUtil.create(new RxUtil.Callback<List<SelectMediaEntity>>() {
            @Override
            public void doBackground(ObservableEmitter<List<SelectMediaEntity>> emitter) {
                List<SelectMediaEntity> listSys = MediaLoadManager.loadAllMediaData(mContext, PhotoConfig.Mode.PHOTO);
                emitter.onNext(listSys);
            }

            @Override
            public void accept(List<SelectMediaEntity> selectMediaEntities) {
                long size = 0;
                if (selectMediaEntities != null && selectMediaEntities.size() > 0) {
                    for (SelectMediaEntity bean : selectMediaEntities) {
                        size = bean.getSize() + size;
                    }
                    mDataBinding.tvPictureNum.setText(selectMediaEntities.size() + getString(R.string.file_num));
                } else {
                    mDataBinding.tvPictureNum.setText(0 + getString(R.string.file_num));
                }
                if (size > 0) {
                    mDataBinding.tvPictureSize.setText(ConvertUtils.byte2FitMemorySize(size, 1));
                    int progress = (int) ((size / memory) * 100f);
                    mDataBinding.sbPicture.setProgress(Math.max(progress, 5));
                } else {
                    mDataBinding.tvPictureSize.setText("0MB");
                }
            }
        });
    }

    //获取视频大小
    private void getVideoNum(long memory) {
        RxUtil.create(new RxUtil.Callback<List<SelectMediaEntity>>() {
            @Override
            public void doBackground(ObservableEmitter<List<SelectMediaEntity>> emitter) {
                List<SelectMediaEntity> listSys = MediaLoadManager.loadAllMediaData(mContext, PhotoConfig.Mode.VIDEO);
                emitter.onNext(listSys);
            }

            @Override
            public void accept(List<SelectMediaEntity> selectMediaEntities) {
                long size = 0;
                if (selectMediaEntities != null && selectMediaEntities.size() > 0) {
                    for (SelectMediaEntity bean : selectMediaEntities) {
                        size = bean.getSize() + size;
                    }
                    mDataBinding.tvVideoNum.setText(selectMediaEntities.size() + getString(R.string.file_num));
                } else {
                    mDataBinding.tvVideoNum.setText(0 + getString(R.string.file_num));
                }
                if (size > 0) {
                    mDataBinding.tvVideoSize.setText(ConvertUtils.byte2FitMemorySize(size, 1));
                    int progress = (int) ((size / memory) * 100f);
                    mDataBinding.sbVideo.setProgress(Math.max(progress, 5));
                } else {
                    mDataBinding.tvVideoSize.setText("0MB");
                }
            }
        });
    }

    //获取文档大小
    private void getDocNum(long memory) {
        //设置获取的数据类型
        List<String> type = new ArrayList<>();
        type.add("application/msword");
        type.add("application/vnd.ms-excel");
        type.add("application/vnd.ms-powerpoint");
        type.add("application/pdf");
        type.add("text/plain");
        RxUtil.create(new RxUtil.Callback<List<MyDocumentBean>>() {
            @Override
            public void doBackground(ObservableEmitter<List<MyDocumentBean>> emitter) {
                List<MyDocumentBean> list = new ArrayList<>();
                List<MediaInfo> infoList = MediaLoader.loadDoc(type);
                if (infoList != null && infoList.size() > 0) {
                    for (MediaInfo bean : infoList) {
                        list.add(new MyDocumentBean(bean.getPath(), bean.getUri(), bean.getName(), bean.getSize(), TimeUtils.millis2String(FileUtils.getFileLastModified(bean.getPath()), "yyyy-MM-dd"), false));
                    }
                }
                emitter.onNext(list);
            }

            @Override
            public void accept(List<MyDocumentBean> list) {
                if (list.size() > 0) {
                    long size = 0;
                    for (MyDocumentBean bean : list) {
                        size = bean.getSize() + size;
                    }
                    mDataBinding.tvDocumentSize.setText(ConvertUtils.byte2FitMemorySize(size, 1));
                    int progress = (int) ((size / memory) * 100f);
                    mDataBinding.sbDocument.setProgress(Math.max(progress, 5));
                    mDataBinding.tvDocumentNum.setText(list.size() + getString(R.string.file_num));
                } else {
                    mDataBinding.tvDocumentSize.setText("0MB");
                    mDataBinding.tvDocumentNum.setText(0 + getString(R.string.file_num));
                }
            }
        });
    }

    //获取音频大小
    private void getAudioNum(long memory) {
        RxUtil.create(new RxUtil.Callback<List<AudioBean>>() {
            @Override
            public void doBackground(ObservableEmitter<List<AudioBean>> emitter) {
                List<AudioBean> audioBeans = MediaLoader.loadAudio();
                emitter.onNext(audioBeans);
            }

            @Override
            public void accept(List<AudioBean> audioBeans) {
                long size = 0;
                if (audioBeans != null && audioBeans.size() > 0) {
                    for (AudioBean bean : audioBeans) {
                        size = bean.getSize() + size;
                    }
                    mDataBinding.tvAudioNum.setText(audioBeans.size() + getString(R.string.file_num));
                } else {
                    mDataBinding.tvAudioNum.setText(0 + getString(R.string.file_num));
                }
                if (size > 0) {
                    mDataBinding.tvAudioSize.setText(ConvertUtils.byte2FitMemorySize(size, 1));
                    int progress = (int) ((size / memory) * 100f);
                    mDataBinding.sbAudio.setProgress(Math.max(progress, 5));
                } else {
                    mDataBinding.tvAudioSize.setText("0MB");
                }
            }
        });
    }

    //获取已安装应用列表大小
    private void getAppNum(long memory) {
        RxUtil.create(new RxUtil.Callback<List<String>>() {
            @Override
            public void doBackground(ObservableEmitter<List<String>> emitter) {
                emitter.onNext(AeUtil.getNoSystemInstalledPackageNames());
            }

            @Override
            public void accept(List<String> list) {
                if (list.size() > 0) {
                    long size = 0;
                    for (String path : list) {
                        size = MyUtils.getAppSize(mContext, path) + size;
                    }
                    mDataBinding.tvAppSize.setText(ConvertUtils.byte2FitMemorySize(size, 1));
                    int progress = (int) ((size / memory) * 100f);
                    mDataBinding.sbApp.setProgress(Math.max(progress, 5));
                    mDataBinding.tvAppNum.setText(list.size() + getString(R.string.file_num));
                } else {
                    mDataBinding.tvAppSize.setText("0MB");
                    mDataBinding.tvAppNum.setText(0 + getString(R.string.file_num));
                }
            }
        });
    }

}